<template>
  <div>
    <div class="search">
      <el-input size="mini" v-model="searchValue" placeholder="请输入项目名称" class="search-input"></el-input>
      <div class="search-btn" @click="handleSearch">查询</div>
    </div>
    <el-scrollbar style="height: calc(100vh - 1vh)">
      <el-tree
        ref="doubleTree"
        :data="treeData"
        :props="defaultProps"
        :expand-on-click-node="false"
        :default-checked-keys="defaultChecked"
        node-key="sfid"
        default-expand-all
      >
        <span slot-scope="{ node, data }" class="custom-tree-node" @click="handleClick(node)">
          <img v-if="node.data.pswz" :src="currentNode === node.id ? activeCameraUrl : cameraUrl" />
          <span :title="getLabel(node)" class="treeLabel" :style="{ color: currentNode === node.id ? '#08e6fa' : '#fff' }">{{
            getLabel(node)
          }}</span>
        </span>
      </el-tree>
    </el-scrollbar>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Watch } from 'vue-property-decorator'
import { getJkxmList } from '@/assets/modules/service'
import { getModules } from '~/assets/modules/arcgisAPI'
import store from '~/assets/modules/store'

@Component({
  name: 'ProjectTree',
  components: {}
})
export default class extends Vue {
  treeLoading: boolean = false
  defaultProps = {
    children: 'jksbList',
    label: 'xmmc'
  }
  currentNode = ''
  activeCameraUrl = require('@/assets/images/panels/shipintubiaodianjihou.png')
  cameraUrl = require('@/assets/images/panels/shipintubiaodianjiqian.png')
  defaultChecked: any[] = []
  searchValue: string = ''
  treeKey: string = ''
  treeData: any = []
  params: any = {}
  defaultExpandedKeys: any = []
  evt: any = null
  layer: any = null
  symbol = {
    type: 'picture-marker',
    url: require('../../assets/images/points/xiangmujiankong.png'),
    width: '28px',
    height: '41px'
  }
  get areaType() {
    return this.$store.getters['videoData/areaType']
  }
  get view() {
    return store.mapView
  }
  @Watch('areaType')
  handleAreaType() {
    setTimeout(() => {
      this.getGridInfo(this.areaData)
    })
  }
  get areaData() {
    return this.$store.getters['videoData/areaData']
  }
  @Watch('areaData', { deep: true })
  handleAreaData() {
    if (this.loaded2d) {
      setTimeout(() => {
        this.getGridInfo(this.areaData)
      })
    }
  }
  get loaded2d() {
    return this.$store.getters['view/loaded2d']
  }
  @Watch('loaded2d')
  handleLoaded2d(val: any) {
    if (val) {
      setTimeout(() => {
        this.getJkxmList()
      }, 3000)
    }
  }

  beforeDestory() {
    if (this.layer) {
      this.view.map.remove(this.layer)
      this.layer = null
    }
  }
  getGridInfo(data: any) {
    const params: any = {}
    if (data.queryType === 1) {
      if (data.gridId) {
        params.gridId = data.gridId
      } else {
        params.xzqhdm = data.areaCode
      }
    } else if (data.areaType === 1) {
      params.xzqhdm = data.areaCode
    } else if (data.areaType === 2) {
      params.sqh = data.areaCode
    } else if (data.areaType === 3) {
      params.jdh = data.areaCode
    }
    if (this.searchValue.length) {
      params.xmmc = this.searchValue
    }
    this.params = params
    this.getJkxmList(params)
  }
  getJkxmList(params?: any) {
    const loading = this.$loading({
      lock: true,
      text: '项目列表查询中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    let data: any = {}
    if (params) {
      data = { ...params }
    }
    this.treeData = []
    getJkxmList(data).then((res: any) => {
      loading.close();
      console.log(res)
      if (res?.data) {
        this.treeData = res.data
        this.createMapIcon(this.treeData)
        this.bindClickEvt()
      }
    })
  }
  async createMapIcon(treeData: any[]) {
    const modules = await getModules(['esri/Graphic', 'esri/layers/GraphicsLayer'])
    const [Graphic, GraphicsLayer] = modules
    if (this.layer) {
      this.layer.graphics.removeAll()
    } else {
      this.layer = new GraphicsLayer()
      console.log(this, this.view)

      if (this.view){
        store.mapView.map.add(this.layer)
        this.view.map.add(this.layer)
      }else {
        setTimeout(() => {
          store.mapView.map.add(this.layer)
          this.view.map.add(this.layer)
        }, 10000)
      }
    }
    console.log('ffffffff111111')

    treeData.forEach((el: any) => {
      const { xzb, yzb } = el
      if (xzb && yzb) {
        const graphic = new Graphic({
          geometry: {
            x: xzb,
            y: yzb,
            type: 'point',
            spatialReference: store.spatialReference
          },
          symbol: this.symbol,
          attributes: { ...el }
        })
        console.log(this.layer)

        this.layer.add(graphic)
      }
    })
  }
  // 绑定地图点击事件
  bindClickEvt() {
    if (this.evt) {
      this.evt.remove()
      this.evt = null
    }
    if (this.view) {
      this.evt = this.view.on('click', (e: any) => {
        this.view.hitTest(e, this.view.graphics).then((res: any) => {
          // this.$store.commit("panel/setLeftPanelShow", true);
          const results = res.results
          if (results.length) {
            const equipmentData = results[0].graphic.attributes
            this.$store.commit('videoData/setEquipmentData', equipmentData)
            this.$store.commit('videoData/setProjectInfo', equipmentData)
            this.$store.commit('videoPanel/setRightPanelShow', true)
            this.$store.commit('videoPanel/setBottomPanelShow', true)
            this.$store.commit('videoPanel/setRightPanel', 'Video')
            this.$store.commit('videoPanel/setBottomPanel', 'Video')
          }
        })
      })
    }
  }
  handleSearch() {
    const params = { ...this.params, xmmc: this.searchValue }
    this.getJkxmList(params)
  }
  handleClick(node: any) {
    console.log('handleClick')
    this.currentNode = node.id
    let data = node.data
    const equipmentData = this.getVideoData(node)
    equipmentData.currentId = node.id
    if (node.level === 2) {
      data = node.parent.data
    }
    this.goToViewAddress(data)
    this.$store.commit('videoData/setEquipmentData', null)

    this.$store.commit('videoData/setProjectInfo', data)
    this.$store.commit('videoData/setCurrentVideo', node.data)
    this.$store.commit('videoPanel/setRightPanelShow', true)
    this.$store.commit('videoPanel/setBottomPanelShow', true)
    this.$store.commit('videoPanel/setRightPanel', 'Video')
    this.$store.commit('videoPanel/setBottomPanel', 'Video')
    this.$store.commit('videoData/setEquipmentData', equipmentData)
    console.log(this.$store.getters['videoData/equipmentData'])
    this.$forceUpdate()
  }
  async goToViewAddress(data: any) {
    try {
      const modules = await getModules(['esri/geometry/Point'])
      const [Point] = modules
      const point = new Point({
        x: data.xzb,
        y: data.yzb,
        spatialReference: store.spatialReference
      })
      store.mapView.goTo({
        target: point
      })
    } catch (error) {
      console.log(error)
    }
  }
  getVideoData(node: any) {
    try {
      if (node.level === 1) {
        return node.data
      } else if (node.level === 2) {
        return node.parent.data
      }
      return node.data
    } catch (error) {
      console.log(error)
      return null
    }
  }
  getLabel(node: any) {
    if (node.data.sbmc) return node.data.sbmc
    if (node.data.xmmc) return node.data.xmmc
    return node.label
  }
}
</script>

<style lang="scss" scoped>
.search {
  display: flex;
  font-family: AlibabaPuHuiTi_2_45_Light;
  font-size: 14px;
  line-height: 30px;
  color: #ffffff;
  .search-input {
    width: 320px;
    margin: 0 10px;
  }
  .search-btn {
    width: 78px;
    height: 28px;
    background-image: url(../../assets/images/dialogs/chaxunanniu-qian.png);
    background-size: 100% 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: AlibabaPuHuiTi_2_65_Medium;
    font-size: 14px;
    color: #ffffff;
  }
}
.custom-tree-node {
  width: 100%;
}
</style>
<style lang="scss">
.el-tree {
  background: #001022;
  color: #fff;
}
.el-tree-node:focus > .el-tree-node__content {
  background-color: #0e4870a3;
}
.el-tree-node__content:hover {
  background-color: #0e4870a3;
}
.el-tree-node__expand-icon {
  color: #08ebff;
}
</style>
